package com.wyx.controller;

import com.wyx.pojo.Result;
import com.wyx.pojo.User;
import com.wyx.service.UserService;
import com.wyx.utils.JwtUtil;
import com.wyx.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{3,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_&-]{6,16}$") String password) {
//        ^\S{3,16}$匹配3-16位非空白字符，^[a-zA-Z0-9_&-]{6,16}$匹配6-16位由字母、数字、下划线、连字符组成的字符。
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        System.out.println(user);
        List<User> users = userService.selectUserByAll(user);
        System.out.println(users.size());
        if (!users.isEmpty()) {
            return Result.error("用户名已存在");
        }
        return Result.success(userService.insertUser(user));
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{3,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_&-]{6,16}$") String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        List<User> users = userService.selectUserByAll(user);
        if (users.isEmpty()) {
            return Result.error("用户名或密码错误");
        } else if (users.size() > 1) {
            return Result.error("系统错误");
        } else {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", users.get(0).getId());
            claims.put("username", username);
            String token = JwtUtil.createToken(claims);
            ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
            valueOperations.set(token, username, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
    }

    @GetMapping("/userInfo")
    public Result userInfo(/*@RequestHeader(name= "Authorization") String token*/) {
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = new User();
        user.setUsername((String) map.get("username"));
        return Result.success(userService.selectUserByAll(user).get(0));
    }
    @GetMapping("/lookUser")
    public Result lookUser(Integer data){
        System.out.println("lookUser:");
        System.out.println(data);
        User user = new User();
        user.setId(data);
        return Result.success(userService.selectUserByAll(user).get(0));
    }

    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody/*自动装配*/ @Validated/*参数校验*/ User user) {
        Map<String, Object> map = ThreadLocalUtil.get();
        user.setId((int) map.get("id"));
        return Result.success(userService.updateUserById(user));
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL/*地址校验*/ String icon) {
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = new User();
        user.setId((int) map.get("id"));
        user.setIcon(icon);
        return Result.success(userService.updateUserById(user));
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> pwd, @RequestHeader(name = "Authorization") String token) {
        String oldPwd = pwd.get("oldPwd");
        String newPwd = pwd.get("newPwd");
        String rePwd = pwd.get("rePwd");
        if (oldPwd.isEmpty() || newPwd.isEmpty() || rePwd.isEmpty())
            return Result.error("缺少必要的参数");
        if (!newPwd.equals(rePwd))
            return Result.error("确认密码与新密码不一致");
        User user = new User();
        Map<String, Object> map = ThreadLocalUtil.get();
        user.setId((int) map.get("id"));
        user.setPassword(oldPwd);
        if (userService.selectUserByAll(user).isEmpty())
            return Result.error("原密码不正确");
        user.setPassword(newPwd);
        userService.updateUserById(user);
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.getOperations().delete(token);
//        valueOperations.set(token,user.getUsername(),1, TimeUnit.HOURS);
        return Result.success();
    }

    @GetMapping("/queryByCreateTime")
    public Result queryByCreateTime() {
        User user = new User();
        user.setUpdateTime(LocalDateTime.parse("2025-02-24T16:07:05"));
        return Result.success(userService.selectUserByAll(user));
    }
}
